package com.powernode.ssm.interceptor;

import com.powernode.ssm.utils.IpUtils;
import com.powernode.ssm.utils.SpringUtils;
import com.powernode.ssm.utils.ThreadLocalContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private SpringUtils springUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String requestURI = request.getRequestURI(); // 获取当前请求的 URI
//        System.out.println("[TokenInterceptor] 拦截到的请求 URI = " + requestURI);

        String token = springUtils.getToken(request, response);

        if (token == null) {
            // 拦截，不放行
            return false;
        }

        // 将 token 存入 ThreadLocal
        ThreadLocalContext.setToken(token);

        // 将 请求IP 存入 ThreadLocal
        ThreadLocalContext.setIp(IpUtils.getClientIp(request));

        // 可选：将 token 放入响应头返回给客户端
        response.setHeader("X-Returned-Token", token);

        return true;
    }

    /**
     * 在请求完成后调用，用于清理 ThreadLocal
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除 ThreadLocal 中的 token，防止内存泄漏
        ThreadLocalContext.clearAll();
    }
}